<template>
    <div class="carousel">
      <div class="carousel-slides">
        <img
          v-for="(image, index) in images"
          :key="index"
          :src="image"
          :style="{left: index * 100 + '%', 'transform': dynamicstyle}"
          alt="暂无图片"
        />
      </div>
    </div>
  </template>
  <script>
import image1 from '../../../assets/001.jpeg';
import image2 from '../../../assets/002.jpeg';
import image3 from '../../../assets/003.jpeg';

  export default {
    data() {
      return {
        images: [
          image1,
          image2,
          image3
        ],
        dynamicstyle: "", //动态样式
        currentSlide: 0, //播放序号
        interval: Object,
      }
    },
    mounted() {
      // 自动播放动画
      this.startSlideshow()
    },
    methods: {
      nextSlide() {
        // 每次指针加一
        this.currentSlide = (this.currentSlide + 1) % this.images.length
        this.setStyle();
      },
      prevSlide() {
        // 每次减一，为负数时循环
        this.currentSlide = (this.currentSlide - 1 + this.images.length) % this.images.length;
        this.setStyle();
      },
      // 图片动画
      setStyle() {
        this.dynamicstyle = `translatex(-${this.currentSlide*100}%)`
      },
      // 定时器
      startSlideshow() {
        this.interval = setInterval(() => {
          this.currentSlide = (this.currentSlide + 1) % this.images.length;
          this.setStyle();
        }, 3000)
      },
      stopSlideshow() {
        clearInterval(this.interval)
      }
    }
  }
  </script>
  <style scoped>
  .carousel {
    
    margin: 6rem 0 0 0;
    position: relative;
  }
  .carousel-slides {
    position: relative;
    width: 100%;
    height: 35rem;
    overflow: hidden;
  }
  .carousel-slides img {
    display: inline-block;
    position: absolute;
    width: inherit;
    margin: 0;
    padding: 0;
    top: 0;
    left: 0;
    height: 100%;
    transition: 0.5s transform ease-in-out;
  }
  .carousel-controls {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    justify-content: center;
  }
/* 手机端适配 */
@media (max-width: 768px) {
    .carousel-slides {
    height: 12.5rem;
  }
}
</style>
  
  
  